package com.quantgroup.data.saastest.aspect;

import com.quantgroup.data.saastest.annotation.DataSource;
import com.quantgroup.data.saastest.config.DynamicDataSource;
import com.quantgroup.saas.dynamicdatasources.SaasParameter;
import com.quantgroup.saas.dynamicdatasources.TenantVo;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

/**
 * @author yangjinhua
 */
@Slf4j
@Aspect
@Component
@Order(-10)
public class DynamicDataSourceAspect {

    @Pointcut("execution(* com.quantgroup.data.saastest.service.impl..*.*(..))")
    public void dataSourcePointCut() {}

    @Pointcut("@annotation(com.quantgroup.data.saastest.annotation.DataSource)")
    public void dataSourceAnnotationPointCut() {}

    @Around("dataSourcePointCut()")
    public Object before(ProceedingJoinPoint joinPoint) {
        log.warn("pointCut-----1111111");
        try {
//            String value = dataSource.value();
//            log.info("--------" + value);
            DynamicDataSource.switchSource(SaasParameter.getTenant().getTenantPrefix());
            log.info("this aspect get datasource by saasparamemter tenant_prefix for datasources key: " + SaasParameter.getTenant().getTenantPrefix());
            return joinPoint.proceed();
        } catch (Throwable e) {
            // TODO Auto-generated catch block
            log.error("switchSource error :" + e.getMessage());
            return null;
        }
    }

    @After("dataSourcePointCut()")
    public void after(JoinPoint joinPoint) {
        log.warn("pointCut-----222222");
        DynamicDataSource.clear();
    }

    @Before("dataSourceAnnotationPointCut() && @annotation(dataSource)")
    public void beforeOpt( DataSource dataSource) {
        log.warn("annotation-----1111111");
        String value = dataSource.value();
        value = value.substring(0, 1).toUpperCase() + value.substring(1);
        TenantVo tenant = SaasParameter.getTenant();
        tenant.setTenantPrefix(tenant.getTenantPrefix() + value);
        DynamicDataSource.switchSource(SaasParameter.getTenant().getTenantPrefix());
    }

    @After("dataSourceAnnotationPointCut()")
    public void afterOpt() {
        log.warn("annotation-----222222");
        DynamicDataSource.clear();
    }


}
